<template>
  <div class="boardlist-container">
    <div style="
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      ">
      <div style="display: flex; align-items: center">
        <el-button type="primary" size="small" @click="addOrEdit(null,1)">新增</el-button>
        <el-button type="warning" size="small" @click="reset">列表重置</el-button>
      </div>
    </div>
    <el-table :data="tableData" ref="machinetoolTable" style="width: 100%" height="85vh" border @selection-change="handleSelectionChange" v-loading="loading">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column align="center" label="机床编号">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center">
        <template slot="header">
          <header-filter title="机床名称" :current-sort="currentSort" props="name" :filter-change="filterChange" :filters="filters.name" />
        </template>
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center">
        <template slot="header">
          <header-filter title="工厂" props="organization" :current-sort="currentSort" :filter-change="filterChange" :filters="filters.organization" />
        </template>
        <template slot-scope="scope">{{ scope.row.organization }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrEdit(scope.row,2)">编辑</el-button>
          <el-button type="text" size="small" style="color:red;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination layout="sizes,total, prev, pager, next, jumper" :current-page="query.page" :page-size="query.pageSize" :page-sizes="[10, 50, 100, 150, 200]" @size-change="handleSizeChange" :total="total" @current-change="handlePageChange"></el-pagination>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false" top="1.5%">
      <div v-loading="dialogLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="left">
          <el-form-item label="机床编号" prop="id">
            <el-input disabled v-model.trim="form.id" placeholder="请输入机床编号" />
          </el-form-item>
          <el-form-item label="机床名称" prop="name">
            <el-input v-model.trim="form.name" placeholder="请输入机床名称" />
          </el-form-item>
          <!-- <el-form-item label="机床IP" prop="ipAddress">
            <el-input v-model.trim="form.ipAddress" placeholder="请输入机床IP" />
          </el-form-item> -->
          <el-form-item label="产线" prop="organizationId">
            <el-select v-model="form.organizationId" filterable placeholder="请选择">
              <el-option v-for="item in allOrgData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-debounce-click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { uniq, findIndex, isString } from 'lodash';
import HeaderFilter from '@/components/headerFilter/HeaderFilter.vue';
import { mapState } from 'vuex';
import globalJs from '@/utils/global';
export default {
  name: 'Boardlist',
  components: { HeaderFilter },
  data() {
    return {
      tableData: [],
      activeName: '0',
      userOrgs: [],
      allMachine: [],
      multipleSelection: [],
      tabList: [],
      currentSort: '',
      filters: {
        company: [],
        name: [],
        organization: []
      },
      filterVals: {
        company: [],
        name: [],
        organization: []
      },
      query: {
        page: 1,
        pageSize: 50
      },
      total: 0,
      open: false,
      form: {
        name: '',
        ipAddress: "",
        organizationId: '',
      },
      rules: {
        name: [
          { required: true, message: "机床名称不能为空", trigger: "blur" },
        ],
        id: [
          { required: true, message: "机床编号不能为空", trigger: "blur" },
        ],
        organizationId: [
          { required: true, message: "产线不能为空", trigger: "change" },
        ]
      },
      dialogTitle: '',
      allOrgData: [],
      dialogLoading: false,
      loading: false
    };
  },
  filters: {
    formDate: (val) => {
      return globalJs.getdate1(val);
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.app.userInfo,
      uploadPartInfo: (state) => state.resource.uploadPartInfo,
      uploadLayoutInfo: (state) => state.resource.uploadLayoutInfo,
      processType: state => state.app.processType
    })
  },
  watch: {
    processType:{
      deep:true,
      handler:function(val,old){
        if(val!=old){
          this.resetAll();
          this.getOrgList();
        }
      }
    }
  },
  mounted() {
    this.getOrgList();
  },
  methods: {
    getOrgList() {
      this.$http
        .get(this.$API.ORGANIZATION, { companyId: this.userInfo.company.id })
        .then(res => {
          let list = Array.isArray(res.data) ? res.data : [];
          list = list.filter(o => { return o.organType == 2 });
          this.allOrgData = list;
          this.machineAjaxMethod()
        })
    },
    //设备
    machineAjaxMethod() {
      this.loading = true;
      let keys = this.allOrgData.map(item => item.id);
      this.$http
        .post(this.$API.MACHINE, keys)
        .then(res => {
          this.loading = false;
          this.allMachine = Array.isArray(res.data) ? res.data : [];
          this.initAjaxMethod();
        })
        .catch(err => {
          this.loading = false;
        });
    },
    initAjaxMethod() {
      let company = [], name = [], organization = [];
      this.allMachine.forEach(item => {
        name.push(item.name);
        organization.push(item.organization);
      });
      this.filters.name = uniq(name).map(o => { return { text: o, value: o }; });
      this.filters.organization = uniq(organization).map(o => { return { text: o, value: o }; });
      this.filterHandler();
    },
    filterChange(code, type, value) {
      if (type === 'checkBox') {
        if (code === 'name') {
          this.filterVals.name = value;
        } else if (code === 'organization') {
          this.filterVals.organization = value;
        }
        this.filterHandler();
      } else if (type === 'sort') {
        this.limitMethod();
      }
    },
    filterHandler() {
      let names = [], organizations = [],
        { name, organization } = this.filterVals,
        orignData = this.allMachine;
      if (name.length > 0) {
        companys.forEach(item => {
          let nameIndex = findIndex(name, o => o == item.name);
          if (nameIndex > -1) {
            names.push(item);
          }
        });
      } else {
        names = orignData;
      }

      if (organization.length > 0) {
        names.forEach(item => {
          let organizationIndex = findIndex(organization, o => o == item.organization);
          if (organizationIndex > -1) {
            organizations.push(item);
          }
        });
      } else {
        organizations = names;
      }

      this.sourceData = organizations;
      this.query.page = 1;
      this.limitMethod();
    },
    reset() {
      this.resetAll();
      this.limitMethod();
    },
    resetAll(){
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.sourceData = this.allMachine;
      this.currentSort = '';
      this.query.page = 1;
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //点击第几页
    handlePageChange(currentPage) {
      this.query.page = currentPage;
      this.limitMethod();
    },
    //点击第几页
    handleSizeChange(currentPage) {
      this.query.pageSize = currentPage;
      this.limitMethod();
    },
    limitMethod() {
      let list = [], { page, pageSize } = this.query;
      for (let i = 0; i < this.sourceData.length; i++) {
        if (i >= ((page - 1) * pageSize) && i < (page * pageSize)) {
          list.push(this.sourceData[i]);
        }
      }
      this.tableData = list;
      this.total = this.sourceData.length;
    },
    getAssteImage(url) {
      return url && isString(url) ? (globalJs.isAbsolutePath(url) ? url : this.$API.ASSERT_SERVER_URL + url) : '';
    },
    addOrEdit(row = null, flag = 1) {
      console.log('row', row)
      this.form = {
        name: flag == 2 ? (row ? row.name : '') : '',
        id: flag == 2 ? (row ? row.id : '') : 'm-' + new Date().getTime(),
        organizationId: flag == 2 ? (row ? row.organizationId : '') : ''
      };
      if (flag == 2) this.form.id = row ? row.id : null;
      this.dialogTitle = flag == 1 ? '添加机床' : '编辑机床';
      this.dialogType=flag;
      this.open = true;
      this.dialogLoading = false;
      this.$nextTick(() => {
        this.$refs['form'].clearValidate();
      })
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (this.dialogType == 2) {
            this.$http.put(this.$API.MACHINE + '/' + this.form.id, this.form, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('修改成功');
              this.open = false;
              this.dialogLoading = false;
              this.machineAjaxMethod();
            })
          } else {
            this.$http.post(this.$API.MACHINE+'/add', this.form, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('添加成功');
              this.open = false;
              this.dialogLoading = false;
              this.machineAjaxMethod();
            })
          }

        }
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const loading = this.$loading({ text: '加载中...' });
        this.$http.del(this.$API.MACHINE + '/' + row.id).then((res) => {
          loading.close();
          this.$message.success('删除成功');
          this.machineAjaxMethod();
        }).catch(e => { loading.close(); })
      });
    },
  }
};
</script>
<style lang="less">
.boardlist-container {
}
</style>
